package dk.android.houseenabler;

import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import dk.android.houseenabler.classes.FileHandle;
import dk.android.houseenabler.classes.HouseEnablerSettings;
import dk.android.houseenabler.classes.ProfilesExporter;
import dk.android.houseenabler.models.Answer;
import dk.android.houseenabler.models.AnswerCollection;
import dk.android.houseenabler.models.House;
import dk.android.houseenabler.models.HouseCollection;

public class SendMailActivity extends Activity {


	private ListView lv;
	private HouseCollection houseCollection;
	private HouseCollection chosenHouseCollection;
	private AnswerCollection answerCollection;
	private ProfilesExporter profExport;

	
//exportEnvironmentProfiles()
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.export_houses_email);
		lv = (ListView) findViewById(R.id.listView_sendmail);

		readHouseCollection();
		chosenHouseCollection = new HouseCollection();
		profExport = new ProfilesExporter();
		
		lv.setAdapter(new ArrayAdapter<House>(this,
				android.R.layout.simple_list_item_multiple_choice,
				houseCollection.getHouses()));
		lv.setTextFilterEnabled(true);

		lv.setItemsCanFocus(false);
		lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

		//Wrapping the selected houses into the chosenHouses list.

		Button btn = (Button) findViewById(R.id.btn_sendmail);
		btn.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) {
				//Cleares previus selections stored in the list.
				chosenHouseCollection.getHouses().clear();
				SparseBooleanArray selection = lv.getCheckedItemPositions();
				String allNotes = "";
				for (int i = 0; i < houseCollection.getHouses().size(); i++) {
					if (selection.valueAt(i)) 
					{
						House house = houseCollection.getHouses().get(i);
						chosenHouseCollection.addHouse(house);
						readAnswerCollection(house.getId());
						allNotes += extractNotes(house.getTitle());
					}
				}
				//readAnswerCollection();
				profExport.exportEnvironmentProfiles(chosenHouseCollection);
				
				writeChosenComments(allNotes);
				EditText address = (EditText)findViewById(R.id.email_address);

				String adr = address.getText().toString();
				sendEmail(adr, "Houseing Enabler Export", "This mail is send from Housing Enabler Android Application");		
				finish();
			}
		});
		
	}
	
	private String extractNotes(String houseTitle)
	{
		String nodesA = "* A *";
		String nodesB = "* B *";
		String nodesC = "* C *";
		String nodesD = "* D *";
		for(Answer ans : answerCollection.getAnswers('a'))
		{
			if(ans != null)	{
				if(ans.getNotes() != null){
						nodesA += ("\r\n"+"Spm: "+ans.getTitle()+"\r\n"+"Note: "+ans.getNotes()+"\r\n"+"-------------------");
				}
			}
		}
		for(Answer ans : answerCollection.getAnswers('b'))
		{
			if(ans != null)	{
				if(ans.getNotes() != null){
						nodesB += ("\r\n"+"Spm: "+ans.getTitle()+"\r\n"+"Note: "+ans.getNotes()+"\r\n"+"-------------------");
				}
			}
		}
		for(Answer ans : answerCollection.getAnswers('c'))
		{
			if(ans != null)	{
				if(ans.getNotes() != null){
						nodesC += ("\r\n"+"Spm: "+ans.getTitle()+"\r\n"+"Note: "+ans.getNotes()+"\r\n"+"-------------------");
				}
			}
		}
		for(Answer ans : answerCollection.getAnswers('d'))
		{
			if(ans != null)	{
				if(ans.getNotes() != null){
						nodesD += ("\r\n"+"Spm: "+ans.getTitle()+"\r\n"+"Note: "+ans.getNotes()+"\r\n"+"-------------------");
				}
			}
		}
		
		return exportNodeBuilder(nodesA,nodesB,nodesC,nodesD,houseTitle);
	}
	private String exportNodeBuilder(String a, String b, String c, String d, String houseTitle)
	{
		String combined = ("\r\n"+"============"+"\r\n"+"="+houseTitle+"\r\n"+"============"+"\r\n"+a +"\r\n"+ b +"\r\n"+ c +"\r\n"+ d);
		
		return combined;
	}
	private void writeChosenComments(String nodes)
	{

		FileHandle fh = new FileHandle();
	
		fh.writeObjectToStorage(HouseEnablerSettings.NODESFILENAME, nodes);
		
	}
	
	private void readHouseCollection() {
		FileHandle fh = new FileHandle(); 
		HouseCollection hc = (HouseCollection)fh.readObjectFromStorage(HouseEnablerSettings.HOUSESCOLLECTIONFILENAME);
        if(hc != null) {
        	this.houseCollection = hc;
        }
	}
	private void readAnswerCollection(int housePosition){
        this.answerCollection = this.houseCollection.getHouse(housePosition).getAnswers();
        if(this.answerCollection == null) {
        	//System.out.println("ER NULL!!!");
        }
	}

	public void sendEmail(String address, String subject, String emailtext)
	{
		try{
			String env = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/dk.android.houseenabler/files/";
		ArrayList<String>filesNames = new ArrayList<String>();
		
		filesNames.add(env+HouseEnablerSettings.ENVIRONMENTFILENAME);
		filesNames.add(env+HouseEnablerSettings.NODESFILENAME);

		
		final Intent emailIntent = new Intent(
		android.content.Intent.ACTION_SEND_MULTIPLE);

		emailIntent.setType("plain/text");
		 
		emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
		new String[] { address });
		 
		emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
		 
		emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, emailtext);
		
		ArrayList<Uri> uris = new ArrayList<Uri>();
		for(String file1 : filesNames)
		{
			File fileIn = new File(file1);
			Uri u = Uri.fromFile(fileIn);
			uris.add(u);
			
		}
		emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
		 
		this.startActivity(Intent
		.createChooser(emailIntent, "Send mail..."));
		 
		} 
	catch (Throwable t) {
		Toast.makeText(this, "Request failed: " + t.toString(),
		Toast.LENGTH_LONG).show();
		}
		
	}

	
}